/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';
import {DeviceEventEmitter, Image, StyleSheet, Text, TouchableOpacity, View,} from 'react-native';
import StyleUtils from "../../res/styles/StyleUtils";
import IparNetwork, {IMAGE_URL, SERVER_TYPE} from "../../httpUtils/IparNetwork";
import CommonUtils from "../../common/CommonUtils";
import I18n from "../../res/language/i18n";
import AlertDialog from "../../custom/AlertDialog";
import IparImageView from "../../custom/IparImageView";

export default class ShopPageListItem extends Component {

    constructor(props) {
        super(props);
        this.iparNetwork = new IparNetwork();
        this.commonUtils = new CommonUtils();

        this.state = {
            isChecked: this.props.isChecked,
            currency_code: this.props.currency_code,
            country: '',
            dataSource: this.props.dataSource,
            soldOutVisible: false,
            goodsNumber: this.props.dataSource.goods_number,
        }
    }


    componentWillReceiveProps(nexProps) {
        this.setState({
            isChecked: nexProps.isChecked,
            dataSource: nexProps.dataSource,
            goodsNumber: nexProps.dataSource.goods_number,
        });


    }


    componentDidMount() {
        CommonUtils.getAcyncInfo('country_iso')
            .then((country) => {
                this.setState({
                    country: country,
                });
            });
    }

    componentWillUnmount() {
        this.commonUtils = null;
    }

    /**
     * 修改购物车里产品数量
     */
    editCart(isAdd) {


        let _goodsNumber = this.state.goodsNumber;
        if (isAdd) {
            _goodsNumber++
        } else {
            if (_goodsNumber > 1) {
                _goodsNumber--
            } else {
                return
            }
        }


        CommonUtils.showLoading();


        let formData = new FormData();
        formData.append('cart_id', this.state.dataSource.cart_id);
        formData.append('goods_number', _goodsNumber);

        this.iparNetwork.getPostFrom(SERVER_TYPE.adminIpar + "editCart", formData)
            .then((result) => {
                console.log(result);
                if (result.code === 200) {
                    this.props.updateGoodsInfo(_goodsNumber);
                    DeviceEventEmitter.emit('toast', I18n.t('default.success'));
                    this.setState({
                        goodsNumber: _goodsNumber,
                    });
                } else if (result.code === 504) {
                    this.setState({
                        soldOutVisible: true,
                    })
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));

                }
                CommonUtils.dismissLoading();
            })
            .catch((error) => {
                console.log('ShopPageListItem---editCart--error: ', error);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                CommonUtils.dismissLoading();

            })

    }


    render() {
        let source = this.state.isChecked ? require('../../res/images/ic_check_box.png') : require('../../res/images/ic_check_box_outline_blank.png');

        let data = this.state.dataSource;


        let goodsName = '';
        if (data) {
            //goods name
            goodsName = data.goods_local_name;
            if (this.state.country === 'CN') {
                if (I18n.locale === 'uy') {
                    goodsName = data.goods_name;
                }
            } else {
                if (I18n.locale === 'ru') {
                    goodsName = data.goods_name;
                }
            }
        }
        let {userData} = this.props;

        return (
            <View style={[StyleUtils.flex, StyleUtils.center, StyleUtils.rowDirection, styles.viewBox]}>

                <TouchableOpacity
                    onPress={() => {
                        this.props.onPress(!this.state.isChecked);
                        this.setState({
                            isChecked: !this.state.isChecked,
                        });
                    }}>
                    <Image
                        source={source}
                        style={[StyleUtils.tabIconSize, {marginRight: 16}]}/>
                </TouchableOpacity>

                {/*tight view*/}
                <View style={StyleUtils.flex}>
                    {/**top view*/}
                    <View style={StyleUtils.rowDirection}>


                        <IparImageView width={86} height={86} url={data.image}/>

                        <Text
                            numberOfLines={2}
                            style={[StyleUtils.text, styles.goodsText,]}>
                            {goodsName}
                        </Text>

                        <TouchableOpacity
                            onPress={this.props.deleteGoods}
                        >
                            <Image
                                style={{
                                    width: 14, height: 14,
                                }}
                                source={require('../../res/images/ic_close.png')}/>
                        </TouchableOpacity>
                    </View>
                    {/**bottom view*/}
                    <View style={[StyleUtils.justifySpace, StyleUtils.marginTop]}>
                        <View style={[StyleUtils.justifySpace, styles.addBox]}>
                            <TouchableOpacity
                                onPress={() => this.editCart(false)}
                                style={[styles.addImageBox, StyleUtils.center]}>
                                <Image
                                    resizeMode='cover'
                                    style={styles.addImage}
                                    source={require('../../res/images/ic_reduce.png')}
                                />
                            </TouchableOpacity>
                            <Text style={[StyleUtils.text, StyleUtils.smallFont, styles.goodsNumView]}>
                                {this.state.goodsNumber}
                            </Text>
                            <TouchableOpacity
                                onPress={() => this.editCart(true)}
                                style={[styles.addImageBox, StyleUtils.center]}>
                                <Image
                                    resizeMode="cover"
                                    style={styles.addImage}
                                    source={require('../../res/images/ic_add.png')}/>
                            </TouchableOpacity>
                        </View>

                        <View style={{alignItems: 'flex-end'}}>
                            <Text style={[StyleUtils.text, StyleUtils.smallFont, {padding: 0, color: 'black'}]}>
                                {(data.goods_pv * this.state.currency_code.swap_amount).toFixed(1)}{this.state.currency_code.currency_code}
                            </Text>
                            {this.getVipPrice(data)}
                        </View>
                    </View>
                </View>


                <AlertDialog
                    requestClose={() => {
                        this.setState({
                            soldOutVisible: false,
                        });
                    }}
                    visible={this.state.soldOutVisible}
                    // centerIcon={require('../../res/ic_sold_out.png')}
                    contentTv={I18n.t('o.soldOut')}
                    centerSts={'ok'}
                    singleBtnOnclick={() => {
                        this.setState({
                            soldOutVisible: false,
                        })
                    }}/>

            </View>
        );
    }


    /**
     *
     */
    getVipPrice(goodsInfo) {
        if (!this.props.userData) return null;
        if (!goodsInfo) return null;
        let swapAmount = this.state.currency_code.swap_amount;

        let price = this.commonUtils.getNewVipPrice(this.props.userData, goodsInfo, swapAmount);
        if (price <= 0) return null;
        return (<View style={[StyleUtils.rowDirection, StyleUtils.center]}>
            <Text style={[styles.goodsImageTitle, {marginTop: 8, minWidth: 10}]}>
                {this.props.userData.user_level ? this.props.userData.user_level.level_name : ''} :
            </Text>
            <Text style={[{marginTop: 8, fontSize: 14, marginLeft: 2, minWidth: 10}]}>
                {((price).toFixed(1)) + ' ' + this.state.currency_code.currency_code}
            </Text>
        </View>);
    }


}
const styles = StyleSheet.create({

    goodsIcon: {
        width: 62,
        height: 62,
        resizeMode: 'contain'
    },
    goodsText: {
        flex: 1,
        color: '#333333',
        paddingRight: 0
    },
    goodsNumView: {
        padding: 0,
        fontSize: 14,
        color: '#333'
    },
    viewBox: {
        borderBottomWidth: 1,
        borderColor: '#c3c3c3',
        padding: 16
    },
    addImageBox: {
        width: 22,
        height: 14,
    },
    addImage: {
        width: 8,
        height: 8,
        tintColor: '#a3a3a3',
        resizeMode: 'cover',
    },
    addBox: {
        width: 80,
        borderWidth: 1,
        borderColor: '#a3a3a3',
    },
    goodsImageTitle: {
        backgroundColor: '#ff6056',
        padding: 2,
        fontSize: 12,
        color: 'white'
    },
});
